import NavBar from '@/components/NavBar'
import Input from '@/components/Input/index'
import styles from './index.module.scss'
import { useFormik } from 'formik'
import * as Yup from 'yup'
import { useDispatch } from 'react-redux'
import { getCodes, getToken } from '@/store/action/user'
import { useEffect, useRef, useState } from 'react'
import { Toast } from 'antd-mobile'
import { useHistory } from 'react-router'
type formValues = {
  mobile: string
  code: string
}
export default function Login() {
  const history = useHistory()
  const formik = useFormik({
    initialValues: {
      mobile: '17673849042',
      code: '123231',
    } as formValues,
    onSubmit: async (values) => {
      // console.log('表单数据', values)
      await dispatch(getToken(values))
      Toast.show({ content: '登录成功' })
      history.push('/')
    },
    // validate: (values) => {
    //   const errors = {} as formValues
    //   if (!/^1[3-9]\d{9}$/.test(values.mobile)) {
    //     errors.mobile = '手机号码格式错误'
    //   }
    //   if (!/^\d{6}$/.test(values.code)) {
    //     errors.code = '验证码格式错误'
    //   }
    //   return errors
    // },
    // 表单验证
    validationSchema: Yup.object().shape({
      // 手机号验证规则
      mobile: Yup.string()
        .required('请输入手机号')
        .matches(/^1[3456789]\d{9}$/, '手机号码格式错误'),

      // 手机验证码验证规则
      code: Yup.string()
        .required('请输入验证码')
        .matches(/^\d{6}$/, '验证码6个数字'),
    }),
  })
  const timeId = useRef(0)
  const [time, setTime] = useState(0)
  const dispatch = useDispatch()
  const handleCodes = () => {
    if (time > 0) return
    if (formik.errors.mobile)
      return Toast.show({ content: formik.errors.mobile })
    dispatch(getCodes(formik.values.mobile))
    Toast.show({ content: '发送成功' })
    setTime(60)
    timeId.current = window.setInterval(() => {
      setTime((time) => {
        if (time === 1) clearInterval(timeId.current)
        return time - 1
      })
    }, 100)
  }
  useEffect(() => {
    return () => {
      clearInterval(timeId.current)
    }
  }, [])
  return (
    <div className={styles.root}>
      <NavBar>登录</NavBar>
      <div className="content">
        {/* 标题 */}
        <h3>短信登录</h3>
        <form onSubmit={formik.handleSubmit}>
          {/* 手机号输入框 */}
          <div className="input-item">
            <Input
              className="input"
              name="mobile"
              placeholder="请输入手机号"
              autoComplete="off"
              validate={formik.touched.mobile ? formik.errors.mobile : ''}
              value={formik.values.mobile}
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
            ></Input>
          </div>

          {/* 短信验证码输入框 */}
          <div className="input-item">
            <Input
              className="input"
              name="code"
              placeholder="请输入验证码"
              maxLength={6}
              autoComplete="off"
              errMsg={
                <span onClick={handleCodes}>
                  {time === 0 ? '获取验证码' : `${time}秒后重新发送`}
                </span>
              }
              validate={formik.touched.code ? formik.errors.code : ''}
              value={formik.values.code}
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
            ></Input>
          </div>

          {/* 登录按钮 */}
          <button
            disabled={!formik.isValid}
            type="submit"
            className="login-btn"
          >
            登录
          </button>
        </form>
      </div>
    </div>
  )
}
